<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input
            v-model="filters.keyWord"
            clearable
            maxlength="10"
            placeholder="车名/车牌号"
            @input="verifyLicense($event, 'keyWord', 'filters')"
          ></el-input>
        </el-form-item>
        <el-select v-model="filters.status" clearable placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
        <el-select
          v-model="filters.vehicle_category"
          clearable
          placeholder="请选择"
        >
          <el-option
            v-for="item in filterData"
            :key="item"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
        <el-form-item>
          <el-button type="primary" v-on:click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table
      :data="vehicles"
      highlight-current-row
      v-loading="listLoading"
      @selection-change="selsChange"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <!--设置模板-->
      <el-table-column prop="name" label="车名" width="120" sortable>
      </el-table-column>
      <el-table-column
        prop="license_number"
        label="车牌号"
        width="120"
        sortable
      >
      </el-table-column>
      <el-table-column
        prop="rent"
        label="租车价格 / 小时"
        min-width="80"
        sortable
      >
      </el-table-column>
      <el-table-column prop="status" label="状态" min-width="100" sortable>
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | nodeState">{{
            scope.row.status
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="vehicle_category"
        label="车型"
        min-width="50"
        sortable
      >
      </el-table-column>
      <el-table-column prop="buy_date" label="购买时间" width="160" sortable>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            size="small"
            @click="handleDel(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button
        type="danger"
        @click="batchRemove"
        :disabled="this.sels.length === 0"
        >批量删除</el-button
      >
      <!--<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="20" :total="total" style="float:right;">
			</el-pagination>-->
      <!--新分页条-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="pageSizes"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="float: right"
      >
      </el-pagination>
    </el-col>

    <!-- 编辑\添加界面 -->
    <el-dialog
      :title="title"
      :visible.sync="editFormVisible"
      :close-on-click-modal="false"
      @close="cancel"
      width="30%"
      class="dialog-width"
    >
      <el-form
        :model="editForm"
        label-width="110px"
        :rules="editFormRules"
        ref="editForm"   
        
      >
        <el-form-item label="车名：" prop="name">
          <el-input v-model="editForm.name" auto-complete="off" ></el-input>
        </el-form-item>
        <el-form-item label="车牌号：" prop="license_number">
          <el-input
            v-model="editForm.license_number"
            auto-complete="off"
            maxlength="10"
            @input="verifyLicense($event, 'license_number', 'editForm')"
          ></el-input>
        </el-form-item>
        <el-form-item label="租金(￥/ h)：" prop="rent">
          <el-input v-model="editForm.rent" auto-complete="off" maxlength="6" @input="verify($event,'rent','editForm')"></el-input>
        </el-form-item>
        <el-form-item label="状态：">
          <template>
            <el-radio v-model="editForm.status" label="未知">未知</el-radio>
            <el-radio v-model="editForm.status" label="已租">已租</el-radio>
            <el-radio v-model="editForm.status" label="等待出租"
              >等待出租</el-radio
            >
          </template>
        </el-form-item>
        <el-form-item label="车型：" prop="vehicle_category">
          <el-input
            v-model="editForm.vehicle_category"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="购买时间：">
          <template>
            <div class="block">
              <el-date-picker
                v-model="editForm.buy_date"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions"
              >
              </el-date-picker>
            </div>
          </template>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="cancel" >取消</el-button>
        <el-button
          type="primary"
          @click.native="editSubmit"
          :loading="editLoading"
          >提交</el-button
        >
      </div>
    </el-dialog>
  </section>
</template>

<script>
import util from "@/common/js/util";
//import NProgress from 'nprogress'
import {
  getDepartmentListPage,
  removeDepartment,
  batchRemoveDepartment,
  editDepartment,
  addDepartment,
} from "@/api/api";
// import { Message } from "element-ui";
export default {
  data() {
    return {
      filters: {
        keyWord: "",
        status: "",
        vehicle_category: "",
      },
      options: ["未知", "已租", "等待出租"], //给下拉框查询用的
      catelist: [], //用来装车辆类型的
      vehicles: [], //装列表数据的
      total: 55,
      pageSizes: [5, 10, 15, 20], //分页的规则
      currentPage: 1, //当前页
      pageSize: 10, //每页显示条目个数
      title: "",
      listLoading: false,
      sels: [], //列表选中列
      //新增和修改公用同一套
      editFormVisible: false, //编辑界面是否显示
      // editLoading: false, //模态框
      editFormRules: {
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        license_number:[{ required: true, message: "请输入车牌号", trigger: "blur" }],
        rent:[{ required: true, message: "请输入价格(每小时)", trigger: "blur" }],
        vehicle_category:[{ required: true, message: "请输入车型", trigger: "blur" }],
      },
      //编辑界面数据 准备一个对象用于给后台传递数据 和模型层里面的条条框框绑定
      editForm: {
        id: null, //id
        name: "",
        buy_date: "",
        status: "未知",
        license_number: "",
        rent: null,
        vehicle_category: "",
      },
      pickerOptions: {
          //选择时间不能超过当前日期
          disabledDate(time) {
            return time.getTime() > Date.now();
          }
      }
    };
  },
  filters: {
    //过滤状态颜色
    nodeState(e) {
      let data = {
        已租: "success",
        未知: "info",
        等待出租: "danger",
      };
      return data[e];
    },
  },
  computed: {
     filterData(){
       this.catelist=this.catelist.map(x=>{
         if(x===""){
            return "空"
         }
         return x;
       })
       return this.catelist;
     }
  },
  methods: {
    //八、关键字查询
    search() {
      //查询还是交给查询全部去做，但是为了排除一个bug需要跳转到第一页
      this.currentPage = 1;
      //然后调用查询方法
      this.getVehicles();
    },
    //七、查询所有的车辆类型
    getCateGory() {
      //直接发送请求获取
      this.$http
        .get("/vehicle/cate")
        .then((result) => {
          this.catelist = result.data;
        })
        .catch((result) => {
          this.$message.error("查询车辆类型失败");
        });
    },
    //六、提交按钮执行添加
    editSubmit() {
      //1、在这里可以实现一个校验表单的过程
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          //如果valid为true，就是说校验表单的东西都完成了
          //提示文案
          this.$confirm("确认提交吗？", "温馨提示", { type: "warning" })
            .then(() => {
              //2、开启模态框
              // this.editLoading = true;
              //3、获取到所有的数据
              let para = Object.assign({}, this.editForm);
              //4、发送请求调用接口
              this.$http
                .put("/vehicle", para)
                .then((result) => {
                  this.$message({
                    message: result.data.code == 1 ? "修改成功" : "修改失败",
                    type: result.data.code == 1 ? "success" : "error",
                  });
                  //关闭编辑框
                  this.editFormVisible = false;
                  //获取列表
                  this.getVehicles();
                  this.getCateGory();
                })
                .catch((error) => {
                  console.log(error);
                });
            })
            .catch((error) => {
              console.log(error);
            });
        }
      });
    },
    //五、批量删除
    batchRemove() {
      //在页面选择的时候，会将对象装到sels数组中，这里取出来，变成id数组
      var ids = this.sels.map((item) => item.id);
      console.log(ids);
      this.$confirm("是否删除选中的数据？", "温馨提示", { type: "warning" })
        .then(() => {
          //带着数组调用接口，实现批量删除的功能
          this.$http
            .patch("/vehicle", ids)
            .then((result) => {
              //如果成功了，就打印信息并且重新加载页面
              console.log(result);
              this.getVehicles();
              this.getCateGory();
            })
            .catch((result) => {
              console.log(result);
            });
        })
        .catch((result) => {
          console.log("取消删除操作");
        });
    },
    //四、删除单条的方法
    handleDel(index, row) {
      this.$confirm("是否删除该数据？", "温馨提示", { type: "warning" })
        .then(
          //再设置一个函数，成功了就执行
          () => {
            //获取到id
            let id = row.id;
            //发送axios请求
            this.$http
              .delete("/vehicle/" + id)
              .then((result) => {
                //如果成功了，就打印信息并且重新加载页面
                console.log(result);
                this.getVehicles();
              })
              .catch((result) => {
                console.log(result);
              });
          }
        )
        .catch((result) => {
          console.log("取消删除操作");
        });
    },
    //三、页码发生改变
    handleCurrentChange(val) {
      console.log(val);
      /*把新页码交给模型层的数据,页码发生改变，1，把页码赋值给当前页码，带着一页多少条一起去数据库查*/
      this.currentPage = val;
      console.log(
        "赋值后的当前页：" + this.currentPage + "页总数：" + this.pageSize
      );
      //2、调用getVehicles查询
      this.getVehicles();
    },
    //二、页数发生改变
    handleSizeChange(val) {
      /*分析，页数量发生改变，把数量赋值给模型层*/
      console.log(val);
      console.log(
        "赋值后的当前页：" + this.currentPage + "页总数：" + this.pageSize
      );
      this.pageSize = val;
      //调用depart方法
      this.getVehicles();
    },
    //一、获取车辆列表
    getVehicles() { 
      //1、将数值加到对象里面
      let para = {
        pageSize: this.pageSize,
        currentPage: this.currentPage,
        keyWord: this.filters.keyWord,
        status: this.filters.status,
        vehicle_category: this.filters.vehicle_category==="空"?" ":this.filters.vehicle_category,
      };
      //2、简单写法，显示到列表
      this.$http
        .post("/vehicle", para)
        .then((result) => {
          // console.log(result.data);
          //3、把返回的数值同步到模型层
          this.vehicles = result.data.rows;
          this.total = result.data.total;
        })
        .catch((result) => {
          this.$message.error("查询失败，请刷新重试");
          // console.log("查询失败，请刷新重试");
        });
    },

    //显示编辑界面
    handleEdit(index, row) {
      //给title赋值
      this.title = "编辑";
      this.editFormVisible = true;
      //把当前行的赋值给表单里面 克隆，不克隆有bug
      this.editForm = Object.assign({}, row);
    },
    //显示表单，进行添加
    handleAdd() {
      //给title赋值
      this.title = "新增";
      this.editFormVisible = true; //新增页面打开表单
      //重置表单，如果不重置的话，会很麻烦
      this.editForm = {
        id: null, //id
        name: "",
        buy_date: "",
        status: "未知",
        license_number: "",
        rent: null,
        vehicle_category: "",
      };
      console.log(this.editForm);
    },
    selsChange(sels) {
      this.sels = sels;
    },
    //取消
    cancel(){
      this.editFormVisible = false;
      this.$refs.editForm.resetFields();
    }
  },
  mounted() {
    this.getVehicles();
    this.getCateGory();
  },
};
</script>

<style>
.el-dialog{
  min-width: 400px !important;
}
</style>
